<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class DeliveryOrder extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 车主端获取订单列表
     *
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getList()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $keywords = $this->request->get('keywords');
        $type = $this->request->get('type'); //1 全部 2 运输中 3 异常 4 已完成
        $uid = $this->auth->id;

        if (!$page || !$limit || !$type) {
            $this->error('参数错误');
        }

        $owner = (new \app\admin\model\Owner())->where('uid', $uid)->find();
        if (!$owner) {
            $this->error('您不是车主，无法查看订单');
        }
        $model = new \app\admin\model\DeliveryOrder();
        $query = $model->where('owner_id', $owner->id);

        // 根据不同的 type 条件添加查询条件
        switch ($type) {
            case 2:
                $query->where('status', 0);
                break;
            case 3:
                $query->where('status', 1);
                break;
            case 4:
                $query->where('status', 2);
                break;
        }

        // 复用查询对象进行分页查询和统计
        $list = $query->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->find();
            $list[$key]['driver'] = (new \app\admin\model\Driver())->where('id', $value['driver_id'])->find();
            $list[$key]['project'] = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $list[$key]['project_manager'] = (new \app\admin\model\ProjectManager())->where('id', $value['project_id'])->find();
        }
        $count = $query->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }


    /**
     * 车主端获取我的对账
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function myOrder()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $uid = $this->auth->id;
        $where = [];
        if( !empty($this->request->get("start_time"))  && !empty($this->request->get("end_time"))){
            $start      = $this->request->get("start_time") .   " 00:00:01";
            $end        = $this->request->get("end_time")  .   " 23:59:59";
            $start      = strtotime($start);
            $end        = strtotime($end);
            $where[]    = ["created_at" ,">=" , $start];
            $where[]    = ["created_at" ,"<=" , $end ];
        }
        $model = new \app\admin\model\DeliveryOrder();
        $owner = (new \app\admin\model\Owner())->where('uid', $uid)->find();
        $list = $model->where('owner_id',$owner->id)->where($where)->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car_name'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->value('plate');
            $list[$key]['driver_name'] = (new \app\admin\model\Driver())->where('id', $value['driver_id'])->value('username');
            $project = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $project['company_name'] = (new \app\admin\model\User())->where('id', $project['company_id'])->value('username');
            $m = (new \app\admin\model\ProjectManager())->where('id', $project['manager_id'])->value('uid');
            $project['manager_name'] = (new \app\admin\model\User())->where('id', $m)->value('username');
            $list[$key]['project'] = $project;
        }
        $count = $model->where('owner_id',$owner->id)->where($where)->count();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('获取成功', $data);
    }

    //todo 待完善
    public function myAccount()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $uid = $this->auth->id;
        $where = [];
        if( !empty($this->request->get("start_time"))  && !empty($this->request->get("end_time"))){
            $start      = $this->request->get("start_time") .   " 00:00:01";
            $end        = $this->request->get("end_time")  .   " 23:59:59";
            $start      = strtotime($start);
            $end        = strtotime($end);
            $where[]    = ["created_at" ,">=" , $start];
            $where[]    = ["created_at" ,"<=" , $end ];
        }
        $project_ids = (new \app\admin\model\Project())->where('company_id', $uid)->column('id');
        $model = new \app\admin\model\DeliveryOrder();
        $list = $model->whereIn('project_id',$project_ids)->where($where)->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car_name'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->value('plate');
            $list[$key]['driver_name'] = (new \app\admin\model\Driver())->where('id', $value['driver_id'])->value('username');
            $project = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $project['company_name'] = (new \app\admin\model\User())->where('id', $project['company_id'])->value('username');
            $m = (new \app\admin\model\ProjectManager())->where('id', $project['manager_id'])->value('uid');
            $project['manager_name'] = (new \app\admin\model\User())->where('id', $m)->value('username');
            $list[$key]['project'] = $project;
        }
        $count = $model->whereIn('project_id',$project_ids)->where($where)->count();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('获取成功', $data);
    }
    /**
     * 订单统计
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function orderDetail()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $uid = $this->auth->id;
        $where = [];
        if( !empty($this->request->get("start_time"))  && !empty($this->request->get("end_time"))){
            $start      = $this->request->get("start_time") .   " 00:00:01";
            $end        = $this->request->get("end_time")  .   " 23:59:59";
            $start      = strtotime($start);
            $end        = strtotime($end);
            $where[]    = ["created_at" ,">=" , $start];
            $where[]    = ["created_at" ,"<=" , $end ];
        }
        $model = new \app\admin\model\DeliveryOrder();
        $owner = (new \app\admin\model\Owner())->where('uid', $uid)->find();
        $list = $model->where('owner_id',$owner->id)->where($where)->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->find();
            $list[$key]['driver'] = (new \app\admin\model\Driver())->where('id', $value['driver_id'])->find();
            $project = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $list[$key]['project'] = $project;
            $list[$key]['owner'] = (new \app\admin\model\Owner())->where('id', $value['owner_id'])->find();
            $list[$key]['project_manager'] = (new \app\admin\model\ProjectManager())->where('id', $project->manager_id)->find();
        }
        $count = $model->where('owner_id',$owner->id)->where($where)->count();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('获取成功', $data);
    }

    /**
     * 创建订单
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createOrder()
    {
        $project_id = $this->request->post('project_id');
        $car_id = $this->request->post('car_id');
        $uid = $this->auth->id;
        $driver = (new \app\admin\model\Driver())->where('uid', $uid)->find();
        $projectBind = (new \app\admin\model\ProjectBind())->where('project_id', $project_id)->find();
        $start_img = $this->request->post('start_img');
        $data = [
            'project_id' => $project_id,
            'car_id' => $car_id,
            'driver_id' => $driver->id,
            'owner_id' => $projectBind->owner_id,
            'start_img' => $start_img,
            'status' => 0,
        ];
        $model = new \app\admin\model\DeliveryOrder();
        //同一个车一个时间段内只能运输一个订单
        $order = $model->where('car_id', $car_id)->where('status', 0)->find();
        if ($order) {
            $this->error('当前车已有订单，请先完成订单');
        }
        $order = (new \app\admin\model\DeliveryOrder())->create($data);
        if ($order) {
            $this->success('创建成功');
        } else {
            $this->error('创建失败');
        }
    }

    /**
     * 获取订单列表
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getOrderList()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $keywords = $this->request->get('keywords');
        $type = $this->request->get('type'); //1 全部 2 运输中 3 异常 4 已完成
        $uid = $this->auth->id;

        if (!$page || !$limit || !$type) {
            $this->error('参数错误');
        }

        $driver = (new \app\admin\model\Driver())->where('uid', $uid)->find();

        $model = new \app\admin\model\DeliveryOrder();
        $query = $model->where('driver_id', $driver->id);

        // 根据不同的 type 条件添加查询条件
        switch ($type) {
            case 2:
                $query->where('status', 0);
                break;
            case 3:
                $query->where('status', 1);
                break;
            case 4:
                $query->where('status', 2);
                break;
        }

        // 复用查询对象进行分页查询和统计
        $list = $query->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->find();
            $list[$key]['driver'] = (new \app\admin\model\Driver())->where('id', $value['driver_id'])->find();
            $list[$key]['project'] = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $list[$key]['project_manager'] = (new \app\admin\model\ProjectManager())->where('id', $value['project_id'])->find();
        }
        $count = $query->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 获取订单详情
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOrderDetail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $model = new \app\admin\model\DeliveryOrder();
        $order = $model->where('id', $id)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        $data = [
            'order' => $order,
            'car' => (new \app\admin\model\Car())->where('id', $order['car_id'])->find(),
            'driver' => (new \app\admin\model\Driver())->where('id', $order['driver_id'])->find(),
            'project' => (new \app\admin\model\Project())->where('id', $order['project_id'])->find(),
            'project_manager' => (new \app\admin\model\ProjectManager())->where('id', $order['project_id'])->find(),
            'owner' => (new \app\admin\model\Owner())->where('id', $order['owner_id'])->find(),
        ];
        $this->success('获取成功', $data);
    }

    public function count()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $uid = $this->auth->id;
        $where = [];
        if( !empty($this->request->get("start_time"))  && !empty($this->request->get("end_time"))){
            $start      = $this->request->get("start_time") .   " 00:00:01";
            $end        = $this->request->get("end_time")  .   " 23:59:59";
            $start      = strtotime($start);
            $end        = strtotime($end);
            $where[]    = ["created_at" ,">=" , $start];
            $where[]    = ["created_at" ,"<=" , $end ];
        }
        $model = new \app\admin\model\DeliveryOrder();
        $driver = (new \app\admin\model\Driver())->where('uid', $uid)->find();
        $list = $model->where('driver_id',$driver->id)->where($where)->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['car'] = (new \app\admin\model\Car())->where('id', $value['car_id'])->find();
            $project = (new \app\admin\model\Project())->where('id', $value['project_id'])->find();
            $list[$key]['project'] = $project;
            $list[$key]['owner'] = (new \app\admin\model\Owner())->where('id', $value['owner_id'])->find();
            $list[$key]['project_manager'] = (new \app\admin\model\ProjectManager())->where('id', $project->manager_id)->find();
        }
        $count = $model->where('driver_id',$driver->id)->where($where)->count();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('获取成功', $data);
    }

    /**
     * 异常上报
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function exceptionReporting()
    {
        $project_id = $this->request->get('project_id');
        $uid = $this->auth->id;
        $content = $this->request->get('content');
        $fail_img = $this->request->get('fail_img');
        if (!$project_id || !$content || !$fail_img) {
            $this->error('参数错误');
        }
        $driver = (new \app\admin\model\Driver())->where('uid', $uid)->find();
        $data = [
            'project_id' => $project_id,
            'driver_id' => $driver->id,
            'content' => $content,
            'fail_img' => $fail_img,
            'status' => 1
        ];
        $result = (new \app\admin\model\DeliveryOrder)->save($data);
        if ($result) {
            $this->success('异常上报成功');
        } else {
            $this->error('异常上报失败');
        }
    }
}